<script setup>
import { onLaunch } from '@dcloudio/uni-app';
import { post, get, put } from './api/index';
import { appStore } from '@/sotre/modules/app';

const { userInfo } = toRefs(appStore());

provide('$post', post);
provide('$get', get);
provide('$put', put);

const token = uni.getStorageSync('TOKEN');

onLaunch(e => {
    // #ifdef APP-PLUS
    uni.request({
        url: `${import.meta.env.VITE_API_URL}/platform/appVersion/get`,
        method: 'POST',
        success: res => {
            const data = res.data;
            const appInfo = uni.getAppBaseInfo();
            if (appInfo.appVersion !== data.data.version) {
                uni.showModal({
                    title: '系统提示',
                    content: '检测到新版本，是否更新？',
                    success: res => {
                        if (res.confirm) {
                            const url = data.data.apkSrc;
                            downloadApp(url);
                        }
                    },
                });
            }
        },
    });

    // #endif
    try {
        uni.showLoading({
            title: '服务加载中...',
            mask: true,
        });
        let inviteCode = '';
        // #ifdef H5
        const urlParams = new URLSearchParams(window.location.search);
        inviteCode = urlParams.get('invite');
        if (inviteCode) {
            uni.setStorageSync('inviteCode', inviteCode);
        }
        uni.hideLoading();
        // #endif

        // #ifdef MP-WEIXIN
        const scene = decodeURIComponent(e.query.scene);
        inviteCode = scene.split('=')[1];
        if (inviteCode) {
            uni.setStorageSync('inviteCode', inviteCode);
        }
        // #endif

        if (token) {
            uni.request({
                url: `${import.meta.env.VITE_API_URL}/platform/users/getUserInfo`,
                method: 'POST',
                header: {
                    Authorization: `Bearer ${token}`,
                },
                success: res => {
                    if (res) {
                        if (res.data.code !== 200) {
                            setTimeout(() => {
                                loginFun();
                            }, 1500);
                        } else {
                            const { data } = res;
                            userInfo.value = data.data.platformUsers;
                            uni.setStorageSync(
                                'enterpriseId',
                                data.data.platformUsers.lastEnterpriseId
                            );
                            uni.switchTab({
                                url: '/pages/home/index',
                            });
                            uni.hideLoading();
                        }
                    }
                },
                fail: () => {
                    uni.hideLoading();
                },
            });
        } else {
            uni.hideLoading();
            loginFun();
        }
    } catch (e) {
        uni.hideLoading();
        return uni.redirectTo({
            url: '/pages/index/register',
        });
    }
});

function loginFun() {
    // #ifdef MP-WEIXIN
    uni.login({
        provider: 'weixin',
        success: res => {
            get(`/platform/wx/userInfo/${res.code}`).then(r => {
                if (r) {
                    uni.hideLoading();
                    if (r.data && typeof r.data === 'string') {
                        uni.setStorageSync('OPENID', r.data);
                        uni.redirectTo({
                            url: '/pages/index/index',
                        });
                    } else {
                        uni.setStorageSync('TOKEN', r.data.access_token);
                        uni.setStorageSync(
                            'enterpriseId',
                            r.data.userInfo.platformUsers.lastEnterpriseId
                        );
                        userInfo.value = r.data.userInfo.platformUsers;
                        if (userInfo.value.state !== 0) {
                            return uni.redirectTo({
                                url: '/pages/index/register',
                            });
                        }
                        uni.switchTab({
                            url: '/pages/home/index',
                        });
                    }
                }
            });
        },
    });
    // #endif
    // #ifdef H5 || APP-PLUS
    uni.redirectTo({
        url: '/pages/index/index',
    });
    // #endif
}

// #ifdef APP-PLUS
function downloadApp(url) {
    const task = uni.downloadFile({
        url,
        success: res => {
            uni.showToast({
                title: `下载完成`,
                icon: 'success',
                mask: true,
                duration: 2000,
            });
            // #ifdef APP-PLUS
            // 使用plus.runtime安装APK
            plus.runtime.install(
                res.tempFilePath,
                {
                    force: false,
                },
                function () {
                    uni.showToast({
                        title: '安装成功',
                        icon: 'success',
                    });
                },
                function (e) {
                    uni.showToast({
                        title: '安装失败: ' + e.message,
                        icon: 'none',
                        duration: 3000,
                    });
                }
            );
            // #endif
        },
    });
    task.onProgressUpdate(res => {
        if (res.progress !== 100) {
            uni.showToast({
                title: `下载中...${res.progress}%`,
                icon: 'loading',
                mask: true,
                duration: 500,
            });
        }
    });
}
// #endif
</script>

<style lang="scss">
page {
    .u-navbar__content__title {
        font-weight: bold;
    }
}
</style>
